package com.kujawnode.service.impl;

import com.fasterxml.jackson.databind.util.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kujawnode.constant.Constants;
import com.kujawnode.manager.RedisManager;
import com.kujawnode.mapper.TRoleMapper;
import com.kujawnode.mapper.TUserMapper;
import com.kujawnode.model.TRole;
import com.kujawnode.model.TUser;
import com.kujawnode.model.TUserVO;
import com.kujawnode.query.BaseQuery;
import com.kujawnode.query.UserQuery;
import com.kujawnode.service.UserService;
import com.kujawnode.utils.CacheUtils;
import io.netty.util.internal.StringUtil;
import jakarta.annotation.Resource;
import org.apache.catalina.mbeans.UserMBean;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @Author kujaw
 * @Date 2025/7/9 13:59
 * @注释
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private TUserMapper tUserMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private TRoleMapper tRoleMapper;

    @Resource
    private RedisManager redisManager;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectByLoginAct(username);
        if (tUser == null) {
            throw new UsernameNotFoundException("登录账号不存在");
        }
        //查询一下当前用户角色
        List<TRole> roleList = tRoleMapper.selectByUserId(tUser.getId());
        //字符串的角色列表
        List<String> stringRoleList = new ArrayList<>();
        roleList.forEach(tRole -> {
            stringRoleList.add(tRole.getRole());
        });

        tUser.setRoleList(stringRoleList); //设置用户角色

        return tUser;
    }

    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
        //1.设置PageHelper
        PageHelper.startPage(current, Constants.PAGE_SIZE);
        //2.查询
        List<TUser> userList = tUserMapper.selectUserByPage(BaseQuery.builder().build());
        //3.封装分页数据到PageInfo
        PageInfo<TUser> users = new PageInfo<>(userList);
        return users;
    }

    @Override
    public TUserVO getUserDetail(Integer id) {
        return tUserMapper.selectUserDetailById(id);
    }

    @Override
    public int addUser(UserQuery userQuery) {
        TUser tUser = new TUser();
        //把userQuery属性复制给tUser(复制要求：两个对象属性名和属性类型相同才能复制)
        BeanUtils.copyProperties(userQuery, tUser);

        //密码加密
        tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
        //添加创建时间
        tUser.setCreateTime(new Date());
        //添加创建人ID
        Object principal = SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal();
        Integer creatorId = null;
        if (principal instanceof UserDetails) {
            // 假设你的 TUser 实现了 UserDetails 接口
            creatorId = ((TUser) principal).getId();
        } else if (principal instanceof String) {
            // 匿名用户或未认证的情况，可做默认处理
            creatorId = null; // 或者设置为系统默认值
        }
        tUser.setCreateBy(creatorId);
        return tUserMapper.insertSelective(tUser);
    }

    @Override
    public int updateUser(UserQuery userQuery) {
        TUser tUser = new TUser();
        //把userQuery属性复制给tUser(复制要求：两个对象属性名和属性类型相同才能复制)
        BeanUtils.copyProperties(userQuery, tUser);

        if (StringUtils.hasText(userQuery.getLoginPwd())) {
            //密码加密
            tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
        }

        //添加编辑时间
        tUser.setEditTime(new Date());
        //添加创建人ID
        Object principal = SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal();
        Integer editorId = null;
        if (principal instanceof UserDetails) {
            // 假设你的 TUser 实现了 UserDetails 接口
            editorId = ((TUser) principal).getId();
        } else if (principal instanceof String) {
            // 匿名用户或未认证的情况，可做默认处理
            editorId = null; // 或者设置为系统默认值
        }
        tUser.setEditBy(editorId);
        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Override
    public int batchDeleteUser(List<Integer> ids) {
        int result = tUserMapper.deleteByIds(ids);
        return result;
    }

    @Override
    public int deleteUserById(Integer id) {
        int result = tUserMapper.deleteByPrimaryKey(id);
        return result;
    }

    /**
     * 获取负责人信息
     * 使用redis缓存
     * @return
     */
    @Override
    public List<TUser> getOwner() {
        //1.从redis查询
        //2.如果redis中没有，则查询数据库
        // List<TUser> ownerList = tUserMapper.selectOwner();
        return CacheUtils.getCache(()->{
            //生产，从redis查询数据
            return (List<TUser>)redisManager.getValue(Constants.REDIS_OWNER_KEY);
        },()->{
            //生产，从数据库查询数据
            return tUserMapper.selectOwner();
        },(t)->{
            //消费，把数据写入redis
            redisManager.setValue(Constants.REDIS_OWNER_KEY,t);
        });
    }
}
